package pl.edu.agh.bd2.servlets;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pl.edu.agh.bd2.domain.*;
import pl.edu.agh.bd2.util.HibernateDAO;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


    public LoginServlet() {
        super();
       
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();

		RequestDispatcher view = null; 
	
		if(request.getParameter("login").equals("admin") && request.getParameter("password").equals("admin")){
			view = request.getRequestDispatcher("/registerManagement.jsp");
			
			session.setAttribute("loggedIn", true);
			session.setAttribute("login", "admin");			
						
			view.forward(request, response);
			return;
		}
		else{
			HibernateDAO<User> dao = new HibernateDAO<User>();
			List<User> list = dao.get("User");
			for(User user : list){
				if(user.getLogin().equals(request.getParameter("login")) && user.getPassword().equals(request.getParameter("password"))){
					Teacher teacher = (Teacher) user;
					session.setAttribute("loggedIn", true);
					session.setAttribute("login", request.getParameter("login"));
					
					session.setAttribute("teacher", teacher);
					
					for(Subject s : teacher.getSubjects())
						System.out.println(s.getName());
					
					HashSet<Subject> set = new HashSet<Subject>();
					for(Subject s : teacher.getSubjects())
						set.add(s);
					
					session.setAttribute("subjects", set);
										
					view = request.getRequestDispatcher("/subjects.jsp");
					view.forward(request, response);
					return;
				}
			}
		}		
		
		view = request.getRequestDispatcher("/login.jsp");
		view.forward(request, response);
	}	
}
